
#ifndef __IRDA_H__
#define __IRDA_H__

#include "board.h"
#include "stm8l15x.h"
#include "stm8l15x_usart.h"

#define ENABLE_USART_IRQ(IRQ)           { IRDA_USART->CR2 |= IRQ; }
#define DISABLE_USART_IRQ(IRQ)          { IRDA_USART->CR2 &= ~IRQ; }
#define IS_USART_IRQ_ENABLE(IRQ)        (( IRDA_USART->CR2 & IRQ ) ? true : false )

#define IS_USART_IRQ(IRQ)               (( IRDA_USART->SR & IRQ ) ? true : false )

#define IS_USART_TXE_INT                ( IS_USART_IRQ(USART_SR_TXE) && IS_USART_IRQ_ENABLE(USART_CR2_TIEN))
#define IS_USART_TC_INT                 ( IS_USART_IRQ(USART_SR_TC) && IS_USART_IRQ_ENABLE(USART_CR2_TCIEN))
#define IS_USART_RXNE_INT               ( IS_USART_IRQ(USART_SR_RXNE) && IS_USART_IRQ_ENABLE(USART_CR2_RIEN))
#define IS_USART_IDLE_INT               ( IS_USART_IRQ(USART_SR_IDLE) && IS_USART_IRQ_ENABLE(USART_CR2_ILIEN))

#define IRDA_WRITE(X)                   { IRDA_USART->DR = X; }
#define IRDA_READ()                     ( IRDA_USART->DR )

#define CRC_INIT                        0xA1

#define IRDA_BROADCAST                  0

typedef struct {
  uint8_t addr;
  uint8_t mode;
  uint8_t crc;
} sPackage;

typedef struct {
  uint8_t index;
  uint8_t count;
  union {
    sPackage pack;
    uint8_t data[sizeof(sPackage)];
  };
} sIrdaBuffer;

void IrdaWriteMode(uint8_t addr, uint8_t mode);
extern void IrdaReadMode(sPackage pack);
void InitUsartIrda(uint32_t baudrate);

#endif //__IRDA_H__